<template>
  <div class="console-container">
    <div class="top">
      <div class="left">
        <el-input
          placeholder="请输入搜索内容"
          v-model="keyWord"
          class="query"
          @input="onSearch"
        ></el-input>
      </div>
      <div class="right">
        <el-button class="button" @click="handleAddLayerData"
          >新建数据</el-button
        >
        <el-button class="button" @click="store.showWindow = false"
          >关闭菜单</el-button
        >
      </div>
    </div>
    <el-table
      class="table"
      :data="tableData"
      row-class-name="table-row"
      cell-class-name="table-cell"
      header-row-class-name="table-header-row"
      header-cell-class-name="table-header-cell"
    >
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column prop="data" label="数据地址"></el-table-column>
      <el-table-column prop="typeCategory" label="数据格式">
        <template #default="scope">
          {{
            layerTypeMap[scope.row.type] &&
            layerTypeMap[scope.row.type][scope.row.typecategory]
          }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div class="btn-text" @click="handleEdit(scope.row)">编辑</div>
          <el-popconfirm
            title="确定删除吗？"
            cancel-button-type="info"
            @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <div class="btn-text">删除</div>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <teleport to="body">
      <div class="popup_wrapper" v-if="popupVisible">
        <div class="popup">
          <div class="popup_header">
            <span>{{ popupTitle }}</span>
            <i class="el-icon-close" @click="popupVisible = false"></i>
          </div>
          <div class="popup_body">
            <el-row :gutter="10">
              <el-col :span="4">数据层级：</el-col>
              <el-col :span="20">
                <el-select v-model="layerdata.level" placeholder="请选择">
                  <el-option
                    v-for="item in datalevel"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="layerdata.level === 2">
              <el-col :span="4">父节点：</el-col>
              <el-col :span="20">
                <el-select v-model="layerdata.parentId" placeholder="请选择">
                  <el-option
                    v-for="item in firstOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="4">名称：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="layerdata.name"
                  placeholder="请输入名称"
                ></el-input>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="4">定位坐标：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="layerdata.coord"
                  placeholder="(经,纬,高)示例：120.311,30.25,10000，用于展示时的相机定位"
                ></el-input>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="layerdata.level === 2">
              <el-col :span="4">数据类型：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="layerdata.type"
                  placeholder="请选择"
                  @change="onChangeType"
                >
                  <el-option
                    v-for="item in layerTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
            <el-row
              :gutter="10"
              v-if="typeCategoryOption.length && layerdata.level === 2"
            >
              <el-col :span="4">数据格式：</el-col>
              <el-col :span="20">
                <el-select
                  v-model="layerdata.typeCategory"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in typeCategoryOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
            <el-row
              :gutter="10"
              v-if="
                (layerdata.typeCategory === '3dtiles_bim' ||
                  layerdata.typeCategory === '3dtiles_white') &&
                layerdata.level === 2
              "
            >
              <el-col :span="4">模型样式配置:</el-col>
              <el-col :span="20">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 6 }"
                  placeholder="请输入内容"
                  v-model="layerdata.jsonString"
                ></el-input>
              </el-col>
            </el-row>
            <template v-if="layerdata.level === 2">
              <el-row
                :gutter="10"
                v-if="
                  ['tdt', 'gaode', 'baidu', 'tencent'].indexOf(layerdata.typeCategory) !=
                    -1 && !layerdata.data
                "
              >
                <el-col :span="4">影像格式：</el-col>
                <el-col :span="20">
                  <el-select v-model="layerdata.layer" placeholder="请选择">
                    <el-option
                      v-for="item in mapLayerMap[layerdata.typeCategory]"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="4">
                  数据地址：
                  <SvgIcon
                    v-if="layerdata.type == '全景图'"
                    icon="up"
                    style="cursor: pointer; font-size: 12px"
                    @click="filePanoInput.click()"
                  />
                  <SvgIcon
                    v-if="
                      layerdata.typeCategory === 'geojson' ||
                      layerdata.type === '模型'
                    "
                    icon="up"
                    style="cursor: pointer; font-size: 12px"
                    @click="startUploadFile"
                  />
                </el-col>
                <el-col :span="20">
                  <el-input
                    v-if="percentage === 100 && !intermediate"
                    v-model="layerdata.data"
                    placeholder="请输入数据地址"
                  ></el-input>
                  <template v-else>
                    <el-progress
                      v-if="!intermediate"
                      :text-inside="true"
                      :stroke-width="32"
                      :percentage="percentage"
                    />
                    <el-progress
                      v-else
                      :text-inside="true"
                      :percentage="50"
                      :stroke-width="32"
                      :indeterminate="true"
                      :format="() => '生成中...'"
                    />
                  </template>
                </el-col>
              </el-row>
            </template>
            <template
              v-if="
                (layerdata.type === '模型' || layerdata.type == '全景图') &&
                layerdata.data &&
                layerdata.level === 2
              "
            >
              <el-row :gutter="10">
                <el-col :span="4">
                  加载坐标：
                  <el-tooltip content="获取原始坐标信息">
                    <SvgIcon
                      v-if="layerdata.type == '全景图'"
                      icon="c_update"
                      style="cursor: pointer; font-size: 12px"
                      @click="getLocationByUrl"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2">经度:</el-col>
                <el-col :span="layerdata.type === '模型' ? 6 : 16">
                  <el-input
                    type="number"
                    v-model="layerdata.json.position.lng"
                  ></el-input>
                </el-col>
                <template v-if="layerdata.type === '模型'">
                  <el-col
                    :span="4"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                    >绕x旋转角度:</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.rotation.x"
                    ></el-input>
                  </el-col>
                  <el-col
                    :span="4"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                    >方向角:</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.heading"
                    ></el-input>
                  </el-col>
                </template>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="4"></el-col>
                <el-col :span="2">纬度:</el-col>
                <el-col :span="layerdata.type === '模型' ? 6 : 16">
                  <el-input
                    type="number"
                    v-model="layerdata.json.position.lat"
                  ></el-input>
                </el-col>
                <template v-if="layerdata.type === '模型'">
                  <el-col
                    :span="4"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                    >绕y旋转角度</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.rotation.y"
                    ></el-input>
                  </el-col>
                  <el-col
                    :span="4"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                    >俯仰角:</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.pitch"
                    ></el-input>
                  </el-col>
                </template>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="4"></el-col>
                <el-col :span="2">高度:</el-col>
                <el-col :span="layerdata.type === '模型' ? 6 : 16">
                  <el-input
                    type="number"
                    v-model="layerdata.json.position.alt"
                  ></el-input>
                </el-col>
                <template v-if="layerdata.type === '模型'">
                  <el-col
                    :span="4"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                    >绕z旋转角度</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="layerdata.typeCategory.indexOf('3dtile') != -1"
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.rotation.z"
                    ></el-input>
                  </el-col>
                  <el-col
                    :span="4"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                    >滚转角:</el-col
                  >
                  <el-col
                    :span="6"
                    v-if="
                      layerdata.typeCategory == 'gltf' ||
                      layerdata.typeCategory == 'obj'
                    "
                  >
                    <el-input
                      type="number"
                      v-model="layerdata.json.roll"
                    ></el-input>
                  </el-col>
                </template>
              </el-row>
            </template>
            <el-row :gutter="10">
              <el-col :span="4">描述：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="layerdata.description"
                  placeholder="请输入描述"
                ></el-input>
              </el-col>
            </el-row>
            <!-- <el-row
              :gutter="10"
              v-if="layerdata.type === '模型' && layerdata.level === 2"
            >
              <el-col :span="3">模型偏移:</el-col>
              <el-col :span="1">北:</el-col>
              <el-col :span="6">
                <el-input
                  v-model="layerdata.offsetData.offsetnorth"
                  placeholder="请输入北偏移量(单位m，可选)"
                ></el-input>
              </el-col>
              <el-col :span="1">东:</el-col>
              <el-col :span="6">
                <el-input
                  v-model="layerdata.offsetData.offseteast"
                  placeholder="请输入东偏移量(单位m，可选)"
                ></el-input>
              </el-col>
              <el-col :span="1">高:</el-col>
              <el-col :span="6">
                <el-input
                  v-model="layerdata.offsetData.offsetheight"
                  placeholder="请输入高度偏移(单位m，可选)"
                ></el-input>
              </el-col>
            </el-row>-->
          </div>
          <div class="popup_footer">
            <el-button type="primary" @click="saveData" :loading="loading"
              >确定</el-button
            >
            <el-button type="primary" @click="popupVisible = false"
              >取消</el-button
            >
          </div>
        </div>
      </div>
    </teleport>
    <form style="display: none" ref="formDom">
      <input
        type="file"
        ref="fileInput"
        @change="chooseUploadFile"
        style="display: none"
      />
      <input
        type="file"
        ref="filePanoInput"
        @change="choosePanoUploadFile"
        accept=".jpg"
        style="display: none"
      />
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import {
  imageLayerType,
  vecLayerType,
  modelLayerType,
  terrainLayerType,
  layerTypeMap,
} from "../../assets/data/layerData";
import { removeLayer, getLayerByAttr } from "../../../static/CIM/BQGIS-load";
import {
  imageFileUpload,
  senceImageFileUpload,
  getOneKrpano,
  upLoadFile,
  fileUpload,
} from "../../api/file.js";
import uploadBigFile from "../../api/uploadBigFile";
import {
  getAllLayerdata,
  getFirstDatas,
  addLayerdata,
  updateLayerdata,
  deleteLayerdata,
} from "../../api/system.js";
import { useLayerStore } from "../../store/layer";
import { useStore } from "../../store/store";
import SvgIcon from "../../components/SvgIcon.vue";
import { ElMessage } from "element-plus";
const fileInput = ref(); // dom
const filePanoInput = ref();
const formDom = ref();
const layerStore = useLayerStore();
const store = useStore();

const popupTitle = ref("新建数据");
const keyWord = ref("");
const tableData = ref([]);
const typeCategoryOption = ref([]);
const mapLayerMap = {
  tdt: [
    { label: "电子图层", value: "vec_d" },
    { label: "电子注记", value: "vec_z" },
    { label: "电子注记英文", value: "vec_e" },
    { label: " 卫星影像", value: "img_d" },
    { label: " 影像注记", value: "img_z" },
    { label: " 影像注记英文", value: "img_e" },
    { label: " 地形渲染图", value: "ter_d" },
    { label: " 地形渲染图注记", value: "ter_z" },
  ],
  gaode: [
    { label: "电子图层", value: "vec" },
    { label: "卫星影像", value: "img_d" },
    { label: "影像注记", value: "img_z" },
    { label: "实时路况信息", value: "time" },
  ],
  baidu: [
    { label: "影像注记", value: "img_z" },
    { label: "实时路况信息", value: "time" },
    { label: "街景覆盖图层", value: "streetview" },
    { label: "自定义样式_暗黑", value: "custom_dark" },
    { label: "自定义样式_午夜", value: "custom_midnight" },
    { label: "自定义样式_灰度图", value: "custom_grayscale" },
    { label: "自定义样式_.强边界风格", value: "custom_hardedge" },
    { label: "自定义样式_谷歌风格", value: "custom_googlelite" },
    { label: "自定义样式_高亮", value: "custom_light" },
    { label: "自定义样式_红色", value: "custom_redalert" },
    { label: "自定义样式_粉色", value: "custom_pink" },
    { label: "自定义样式_绿色", value: "custom_grassgreen" },
    { label: "自定义样式_深绿色", value: "custom_darkgreen" },
    { label: "自定义样式_青色", value: "custom_bluish" },
  ],
  baidu: [
    { label: "影像注记", value: "img_z" },
    { label: "实时路况信息", value: "time" },
    { label: "街景覆盖图层", value: "streetview" },
    { label: "自定义样式_暗黑", value: "custom_dark" },
    { label: "自定义样式_午夜", value: "custom_midnight" },
    { label: "自定义样式_灰度图", value: "custom_grayscale" },
    { label: "自定义样式_.强边界风格", value: "custom_hardedge" },
    { label: "自定义样式_谷歌风格", value: "custom_googlelite" },
    { label: "自定义样式_高亮", value: "custom_light" },
    { label: "自定义样式_红色", value: "custom_redalert" },
    { label: "自定义样式_粉色", value: "custom_pink" },
    { label: "自定义样式_绿色", value: "custom_grassgreen" },
    { label: "自定义样式_深绿色", value: "custom_darkgreen" },
    { label: "自定义样式_青色", value: "custom_bluish" },
  ],
  tencent: [
    { label: "电子图层", value: "vec" },
    { label: "卫星影像", value: "img_d" },
    { label: "影像注记", value: "img_z" },
    { label: "地形渲染图_灰色", value: "custom_3" },
    { label: "地形渲染图_暗色", value: "custom_4" },
  ],
};
const datalevel = ref([
  { id: 1, name: "根节点" },
  { id: 2, name: "子节点" },
]);
const layerTypeList = ref([
  { id: "1", name: "影像" },
  { id: "2", name: "高程" },
  { id: "3", name: "模型" },
  { id: "4", name: "矢量" },
  { id: "5", name: "全景图" },
]);
const firstOptions = ref([]);
const layerdata = ref({
  id: null,
  name: null,
  type: null,
  coord: null,
  data: null,
  description: null,
  level: null,
  parentId: null,
  sort: 1,
  offsetData: {},
  jsonString: "",
  layer: null,
});
const popupVisible = ref(false);
const loading = ref(false);
const percentage = ref(100);
const intermediate = ref(false);
let time = null; //time用来控制事件的触发

getlayerData();
GetFirstDataList();

watch(
  () => layerdata.value.type,
  (data) => {
    if (data === "影像") {
      typeCategoryOption.value = imageLayerType;
    } else if (data === "矢量") {
      typeCategoryOption.value = vecLayerType;
    } else if (data === "模型") {
      typeCategoryOption.value = modelLayerType;
    } else if (data === "高程") {
      typeCategoryOption.value = terrainLayerType;
    } else {
      typeCategoryOption.value = [];
    }
  }
);

function getLocationByUrl() {
  if (layerdata.value.type == "全景图") {
    const xml = loadXML(layerdata.value.data.replace(/.[^/.]+$/, ".xml"));
    if (!xml) {
      return ElMessage({
        message: "读取全景图地址失败",
        type: "warning",
      });
    }
    const root = xml.documentElement;
    const scenes = root.getElementsByTagName("scene");
    layerdata.value.json.position = {
      lat: Number(scenes[0].getAttribute("lat")),
      lng: Number(scenes[0].getAttribute("lng")),
      alt: Number(scenes[0].getAttribute("heading")),
    };
  } else {
  }
}

function loadXML(xmlFile) {
  var xmlDoc = null;
  var agent = navigator.userAgent.toLowerCase();

  //判断浏览器的类型
  //支持IE浏览器
  if (agent.indexOf("msie") > 0) {
    var xmlDomVersions = [
      "MSXML.2.DOMDocument.6.0",
      "MSXML.2.DOMDocument.3.0",
      "Microsoft.XMLDOM",
    ];
    for (var i = 0; i < xmlDomVersions.length; i++) {
      try {
        xmlDoc = new ActiveXObject(xmlDomVersions[i]);
        break;
      } catch (e) {}
    }
  }
  //支持firefox浏览器
  else if (agent.indexOf("firefox") > 0) {
    try {
      xmlDoc = document.implementation.createDocument("", "", null);
    } catch (e) {}
  } else {
    //谷歌浏览器
    var oXmlHttp = new XMLHttpRequest();
    oXmlHttp.open("GET", xmlFile, false);
    oXmlHttp.send(null);
    return oXmlHttp.responseXML;
  }
  if (xmlDoc != null) {
    xmlDoc.async = false;
    xmlDoc.load(xmlFile);
  }
  return xmlDoc;
}

function startUploadFile() {
  if (!layerdata.value.typeCategory) {
    return ElMessage({
      message: "请先选择数据格式",
      type: "warning",
    });
  }
  if (layerdata.value.typeCategory === "geojson") {
    fileInput.value.accept = ".json";
    fileInput.value.multiple = false;
    fileInput.value.click();
  } else if (layerdata.value.typeCategory.indexOf("3dtiles") !== -1) {
    fileInput.value.accept = ".zip";
    fileInput.value.multiple = false;
    // fileInput.value.webkitdirectory = true;
    fileInput.value.click();
  } else if (layerdata.value.typeCategory.indexOf("gltf") !== -1) {
    fileInput.value.accept = ".glb, .gltf";
    fileInput.value.multiple = false;
    fileInput.value.click();
  } else if (layerdata.value.typeCategory.indexOf("obj") !== -1) {
    fileInput.value.accept = ".obj, .mtl";
    fileInput.value.multiple = true;
    fileInput.value.click();
  }
}

function chooseUploadFile(e) {
  if (layerdata.value.typeCategory === "geojson") {
    upLoadGeoJsonFile(e);
  } else if (layerdata.value.typeCategory.indexOf("3dtiles") !== -1) {
    upLoad3dtileFile(e);
  } else if (layerdata.value.typeCategory === "gltf") {
    upLoadGltfFile(e);
  } else if (layerdata.value.typeCategory.indexOf("obj") !== -1) {
    upLoadObjFile(e);
  }
}

function upLoadGeoJsonFile(e) {
  const files = e.target.files;
  const file = files[0];
  const f = new FormData();
  f.append("file", file);
  f.append("Module", "geoJson");
  console.log(file, "file");
  console.log(f);
  loading.value = true;
  imageFileUpload(f)
    .then((res) => {
      ElMessage({
        message: "上传成功",
        type: "success",
      });
      layerdata.value.data = res.path;
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: "上传失败",
        type: "warning",
      });
    })
    .finally(() => {
      loading.value = false;
      formDom.value.reset();
    });
}

function upLoad3dtileFile(e) {
  const files = e.target.files;
  const file = files[0];
  const maxSize = 100 * 1024 * 1024;
  if (file.size > maxSize) {
    // 上传大于100m的3dtiles压缩包
    uploadBigFile(
      (state, progress, fileData) => {
        percentage.value = progress;
        if (state === "合并完成") {
          ElMessage({
            message: "上传成功",
            type: "success",
          });
          layerdata.value.data = fileData.path;
          loading.value = false;
          percentage.value = 100;
          formDom.value.reset();
        } else if (state == "合并失败" || state == "分片上传失败，取消上传") {
          ElMessage({
            message: "上传失败",
            type: "success",
          });
          loading.value = false;
          percentage.value = 100;
          formDom.value.reset();
        }
      },
      file,
      {
        module: "tileModel",
      }
    );
  } else {
    // 上传小于100m的3dtiles压缩包
    const f = new FormData();
    f.append("file", file);
    f.append("Module", "tileModel");
    loading.value = true;
    fileUpload(f, (progress) => {
      percentage.value = progress;
    })
      .then((res) => {
        ElMessage({
          message: "上传成功",
          type: "success",
        });
        layerdata.value.data = res.path;
      })
      .catch((err) => {
        console.error(err);
        ElMessage({
          message: "上传失败",
          type: "warning",
        });
      })
      .finally(() => {
        percentage.value = 100;
        loading.value = false;
        formDom.value.reset();
      });
  }
  return;
}

function upLoadGltfFile(e) {
  const files = e.target.files;
  const file = files[0];
  const f = new FormData();
  f.append("file", file);
  f.append("Module", "gltfModel");
  loading.value = true;
  upLoadFile(f, (progress) => {
    percentage.value = progress;
  })
    .then((res) => {
      ElMessage({
        message: "上传成功",
        type: "success",
      });
      layerdata.value.data = res.baseurl + res.data[0];
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: "上传失败",
        type: "warning",
      });
    })
    .finally(() => {
      percentage.value = 100;
      loading.value = false;
      formDom.value.reset();
    });
}

function upLoadObjFile(e) {
  const files = e.target.files;
  const f = new FormData();
  for (let i = 0; i < files.length; i++) {
    f.append("file", files[i]);
    console.log(files[i]);
  }
  f.append("Module", "gltfModel");
  loading.value = true;
  upLoadFile(f, (progress) => {
    percentage.value = progress;
  })
    .then((res) => {
      ElMessage({
        message: "上传成功",
        type: "success",
      });
      layerdata.value.data = res.baseurl + res.data[0];
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: "上传失败",
        type: "warning",
      });
    })
    .finally(() => {
      percentage.value = 100;
      loading.value = false;
      formDom.value.reset();
    });
}

function choosePanoUploadFile(e) {
  const files = e.target.files;
  const file = files[0];
  const f = new FormData();
  f.append("Files", file);
  f.append("Module", "pano");
  f.append("SenceName", getUUId());
  loading.value = true;
  senceImageFileUpload(f, (progress) => {
    percentage.value = progress;
  })
    .then((res) => {
      ElMessage({
        message: "图片上传成功，正在切片生成全景",
        type: "success",
      });
      percentage.value = 100;
      intermediate.value = true;
      return getOneKrpano({ path: res[0] });
    })
    .then((path) => {
      ElMessage({
        message: "创建全景图成功",
        type: "success",
      });
      layerdata.value.data = path;
      getLocationByUrl();
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: "创建全景图失败",
        type: "warning",
      });
    })
    .finally(() => {
      loading.value = false;
      intermediate.value = false;
      percentage.value = 100;
      formDom.value.reset();
    });

  function getUUId() {
    let tem = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    let id = "",
      len = tem.length,
      i = 0;
    for (i; i < len; i++) {
      if (tem[i] == "-") id += tem[i];
      else {
        let num = Math.floor(Math.random() * 16);
        id += num.toString(16);
      }
    }
    return id;
  }
}

function onChangeType(data) {
  layerdata.value.typeCategory = "";
}

function onSearch() {
  if (time !== null) {
    clearTimeout(time);
  }
  time = setTimeout(() => {
    getlayerData();
  }, 500);
}
// 获取父节点数据
function GetFirstDataList() {
  return getFirstDatas().then((res) => {
    firstOptions.value = res.map((item) => {
      return {
        id: item.id,
        name: item.name,
      };
    });
    return res;
  });
}

function getlayerData() {
  return getAllLayerdata({ keyWord: keyWord.value }).then((res) => {
    tableData.value = res;
    return res;
  });
}

function handleAddLayerData() {
  popupTitle.value = "新建数据";
  layerdata.value = {
    id: null,
    name: null,
    type: null,
    coord: null,
    data: null,
    description: null,
    level: null,
    parentId: null,
    sort: 1,
    offsetData: {},
    typeCategory: "",
    jsonString: "",
    json: {
      position: {
        lng: null,
        lat: null,
        alt: null,
      },
      rotation: {
        x: null,
        y: null,
        z: null,
      },
    },
  };
  popupVisible.value = true;
}

function handleEdit(data) {
  popupTitle.value = "编辑数据";
  const defaultJsonData = {
    position: {
      lng: null,
      lat: null,
      alt: null,
    },
    rotation: {
      x: null,
      y: null,
      z: null,
    },
  };
  let json = {};
  try {
    json = data.json
      ? { ...defaultJsonData, ...JSON.parse(data.json) }
      : defaultJsonData;
  } catch (err) {
    console.error(err);
    json = defaultJsonData;
  }
  console.log(data, "data");
  layerdata.value = {
    id: data.id,
    name: data.name,
    type: data.type,
    coord: data.coord,
    data: data.data,
    description: data.description,
    level: data.level,
    parentId: data.parentid,
    sort: data.sort,
    offsetData: data.offsetdata || {},
    typeCategory: data.typecategory,
    jsonString: data.jsonstring,
    json,
    layer: data.layer,
  };
  popupVisible.value = true;
}

async function handleDelete(data) {
  try {
    const res = await deleteLayerdata({ id: data.id });
    await Promise.all([getlayerData(), GetFirstDataList()]);
    removeLayer(viewer, data);
    layerStore.setTreeData();
    ElMessage({
      message: res.msg,
      type: "success",
    });
  } catch (err) {
    console.error(err);
    ElMessage({
      message: "删除失败",
      type: "warning",
    });
  }
}

async function saveData() {
  function isEmpty(obj) {
    // 深拷贝，并去除空值（null,undefined,空字符串）
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === "object") {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (obj[key] && typeof obj[key] === "object") {
            objClone[key] = isEmpty(obj[key]);
          } else {
            if (obj[key] == null || obj[key] == "") continue;
            objClone[key] = obj[key];
          }
        }
      }
    }
    return objClone;
  }

  if (!layerdata.value.name) {
    return ElMessage({
      message: "名称不能为空",
      type: "warning",
    });
  }
  if (!layerdata.value.level) {
    return ElMessage({
      message: "数据层级不能为空",
      type: "warning",
    });
  }
  loading.value = true;
  const params = {};
  for (let key in layerdata.value) {
    // 整理表单数据，将json字段中的空值去除，转换为json字符串
    if (key !== "json") {
      params[key] = layerdata.value[key];
    }
    if (key === "json" && layerdata.value.json) {
      params.json =
        layerdata.type === "模型"
          ? JSON.stringify(isEmpty(layerdata.value.json))
          : JSON.stringify(layerdata.value.json);
    }
  }
  if (popupTitle.value === "新建数据") {
    try {
      const res = await addLayerdata(params);
      await Promise.all([getlayerData(), GetFirstDataList()]);
      layerStore.setTreeData();
      ElMessage({
        message: res.msg,
        type: "success",
      });
      popupVisible.value = false;
    } catch (err) {
      ElMessage({
        message: "添加失败",
        type: "warning",
      });
    } finally {
      loading.value = false;
    }
  } else if (popupTitle.value === "编辑数据") {
    try {
      const res = await updateLayerdata(params);
      await Promise.all([getlayerData(), GetFirstDataList()]);
      layerStore.setTreeData();
      const index = layerStore.checkedKeys.indexOf(layerdata.value.id);
      if (index !== -1) {
        removeLayer(viewer, layerdata.value);
        layerStore.loadLayers(viewer, {
          ...layerdata.value,
          offset: layerdata.value.offsetData,
        });
      }
      ElMessage({
        message: res.msg,
        type: "success",
      });
      popupVisible.value = false;
    } catch (err) {
      console.error(err);
      ElMessage({
        message: "修改失败",
        type: "warning",
      });
    } finally {
      loading.value = false;
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/console.scss";
.el-col-2 {
  font-size: 12px;
  height: 32px;
  line-height: 32px;
}
</style>
